package com.wchat.serviceimpl;

import com.wchat.configurer.RedisPoolConfig;
import com.wchat.dataobject.UserEntity;
import com.wchat.dto.SearchUserDTO;
import com.wchat.enums.ResultEnum;
import com.wchat.exceptions.ServiceException;

import com.wchat.repository.UserRepository;
import com.wchat.service.SearchAroundService;
import com.wchat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchAroundServiceImpl implements SearchAroundService {

    private static final String MEN = "1";
    private static final String WOMEN = "0";

    @Autowired private UserRepository userRepository;

    @Autowired private UserService userService;

    @Override
    public List<SearchUserDTO> searchAround(Integer userId) {

            UserEntity user =  userRepository.findOne(userId);
            if(null == user){
                throw new ServiceException(ResultEnum.CURRENT_USER_NULL.getCode(),ResultEnum.CURRENT_USER_NULL.getValue()); //  当前用户不存在 请查看
            }
            String gender = String.valueOf(user.getGender());
            if(gender == null){
                gender =MEN;  //  如果获取性别失败 默认是 男性
            }
            Jedis jedis =  RedisPoolConfig.getJedis();

             try {
                 // 默认搜索附近 500千米范围的人 根据性别来判断
                 List<GeoRadiusResponse> geoRadiusResponseList = jedis.georadius(String.valueOf(gender).equals(WOMEN) ? String.valueOf(MEN) : String.valueOf(WOMEN),
                         Double.parseDouble(user.getLongitude()), Double.parseDouble(user.getLatitude()),
                         500L, GeoUnit.KM);
                 if (CollectionUtils.isEmpty(geoRadiusResponseList)) {
                     throw new ServiceException(ResultEnum.AURPOUND_NEARBY_NULL.getCode(), ResultEnum.AURPOUND_NEARBY_NULL.getValue()); //  附近暂时没有心仪对象
                 }
                 List<Integer> userIds = geoRadiusResponseList.stream().map(genRadiusResponse -> Integer.valueOf(genRadiusResponse.getMemberByString())).collect(Collectors.toList());
                 List<UserEntity> userEntityList = userRepository.findAll(userIds);
                 userEntityList.stream().filter(x ->x.getUserId() != userId); //
                 if (CollectionUtils.isEmpty(userEntityList)) {
                     throw new ServiceException(ResultEnum.AURPOUND_NEARBY_NULL.getCode(), ResultEnum.AURPOUND_NEARBY_NULL.getValue()); //  附近暂时没有心仪对象
                 }
                 List<Integer> userIdList = userService.followList(userId).stream().map(x ->x.getUserId()).collect(Collectors.toList());

                List<SearchUserDTO> searchUserDTOS =  userEntityList.stream().map(x -> {
                     SearchUserDTO searchUserDTO = new SearchUserDTO();
                     if(userIdList.contains(x.getUserId())){
                        searchUserDTO.setFollow(1);
                     }else {
                        searchUserDTO.setFollow(0);
                    }
                     searchUserDTO.setAge(x.getAge());
                     searchUserDTO.setCity(x.getCity());
                     searchUserDTO.setCountry(x.getCountry());
                     searchUserDTO.setCuteName(x.getCuteName());
                     searchUserDTO.setDegree(x.getDegree());
                     searchUserDTO.setPhoneNumber(x.getPhoneNumber());
                     searchUserDTO.setGender(x.getGender());
                     searchUserDTO.setHeadImage(x.getHeadImage());
                     searchUserDTO.setHeight(x.getHeight());
                     searchUserDTO.setPosition(x.getPosition());
                     searchUserDTO.setIsNew(x.getIsNew());
                     searchUserDTO.setProvince(x.getProvince());
                     searchUserDTO.setUserId(x.getUserId());
                     searchUserDTO.setResidence(x.getResidence());
                     return searchUserDTO;

                 }).filter(x -> x.getUserId() != userId).collect(Collectors.toList());
                 return searchUserDTOS;
             }finally {
                   if(jedis != null){
                       jedis.close();
                   }

             }


    }
}
